package com.sxj.corejava.code11_IO.字节流;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 石小俊
 * 2024年07月29日 14:53
 */
public class Test05_对象输入输出流 {

    public static void main(String[] args) {
        test01();
        test02();
    }

    /**
     * 序列化:将对象转换成二进制数据,可以通过一个文件来存储序列化之后的二进制数据
     */
    public static void test01() {
        User user = new User(1, "admin", "111111");
        User user2 = new User(2, "alice", "222222");
        User user3 = new User(3, "jack", "333333");
        List<User> users = new ArrayList<>(Arrays.asList(user, user2, user3));
        List<Object> list = new ArrayList<>();

        try (
                FileOutputStream out = new FileOutputStream("E:/test/users.data");
                ObjectOutputStream oos = new ObjectOutputStream(out);
        ) {
            //oos.writeObject(1);
            //oos.writeObject("admin");
            //oos.writeObject(true);
            //oos.writeObject(user);
            //oos.writeObject(user2);
            //oos.writeObject(user3);
            //oos.writeObject(users);

            list.add(1);
            list.add("admin");
            list.add(true);
            list.add(user);
            list.add(user2);
            list.add(user3);
            list.add(users);
            oos.writeObject(list);

            oos.flush();
            System.out.println("对象序列化成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 反序列化
     */
    public static void test02() {
        try (
                ObjectInputStream in = new ObjectInputStream(new FileInputStream("E:/test/users.data"));
        ) {
            //System.out.println(in.readObject());
            //System.out.println(in.readObject());
            //System.out.println(in.readObject());
            //System.out.println(in.readObject());
            //System.out.println(in.readObject());
            //System.out.println(in.readObject());
            //System.out.println(in.readObject());

            List<Object> list = (List<Object>) in.readObject();
            for (Object obj : list) {
                System.out.println(obj);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
